// pages/main.js
const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')
const APP = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shops: {},
    banners: [],
    gridItems: [],
    notices: [],
    stores: [],
    pageNum: 1,
    pageSize: 10,
    isLoading: false,
    noMoreData: false,
    keyword: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {


    getApp().initLanguage(this)
    wx.setNavigationBarTitle({
      title: this.data.$t.shop.select,
    })
    this.setData({
      type: options.type,
      shop_join_open: wx.getStorageSync('shop_join_open')
    })
    this.loadBanners();
    this.loadGridItems();
    this.loadNotices();
    this.loadStores();

    console.log("onShow")
    wx.getLocation({
      type: 'wgs84', //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: (res) => {
        this.data.latitude = res.latitude
        this.data.longitude = res.longitude
        console.log("ddddddddd",res.latitude)
        this.fetchShops(res.latitude, res.longitude, '')
      },
      fail(e){
        console.log("checkAndAuthorize")
        console.error(e)
        AUTH.checkAndAuthorize('scope.userLocation')
      }
    }) 


  },
  // onShow: function () {
  //   console.log("onShow")
  //   wx.getLocation({
  //     type: 'wgs84', //wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
  //     success: (res) => {
  //       this.data.latitude = res.latitude
  //       this.data.longitude = res.longitude
  //       console.log("ddddddddd",res.latitude)
  //       this.fetchShops(res.latitude, res.longitude, '')
  //     },
  //     fail(e){
  //       console.log("checkAndAuthorize")
  //       console.error(e)
  //       AUTH.checkAndAuthorize('scope.userLocation')
  //     }
  //   })       
  // },


  async fetchShops(latitude, longitude, kw){
    const res = await WXAPI.fetchShops({
      curlatitude: latitude,
      curlongitude: longitude,
      nameLike: kw
    })
    console.log(res,"res")
    if (res.code == 0) {
      res.data.forEach(ele => {
        ele.distance = ele.distance.toFixed(1) // 距离保留3位小数
      })
      console.log("res.data",res.data)
      this.setData({
        shops: res.data
      })
    } else {
      this.setData({
        shops: null
      })
    }
  },
  searchChange(event){
    this.setData({
      searchValue: event.detail.value
    })
  },
  search(event){
    console.log('search')
    this.setData({
      searchValue: event.detail.value
    })
    this.fetchShops(this.data.latitude, this.data.longitude, event.detail.value)
  },
  goShop(e){
    console.log("eeee",e.currentTarget.dataset.data)
    const idx = e.id   
    wx.setStorageSync('shopInfo', e.currentTarget.dataset.data.id)
    wx.setStorageSync('refreshIndex', 1)
    wx.navigateTo({
      url: '/pages/index/index?id='+e.currentTarget.dataset.data.id
    })
    // if (this.data.type == 'index') {
    //   wx.setStorageSync('refreshIndex', 1)
    // }

    // if (this.data.type == 'pay') {
    //   wx.navigateBack()
    // } else {
    //   wx.switchTab({
    //     url: '/pages/index/index'
    //   })
    // }
    
  },
  joinApply() {
    wx.navigateTo({
      url: '/pages/shop/join-apply',
    })
  },

  /**
   * 加载轮播图数据
   */
  loadBanners() {
    // 模拟轮播图数据，实际项目中应该从服务器获取
    const banners = [
      {
        id: 1,
        imageUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
        linkUrl: '/pages/detail/index?id=1'
      },
      {
        id: 2,
        imageUrl: 'https://img.yzcdn.cn/vant/tree.jpg',
        linkUrl: '/pages/detail/index?id=2'
      },
      {
        id: 3,
        imageUrl: 'https://img.yzcdn.cn/vant/sand.jpg',
        linkUrl: '/pages/detail/index?id=3'
      }
    ];

    this.setData({
      banners: banners
    });
  },

  /**
   * 加载宫格导航数据
   */
  loadGridItems() {
    // 模拟宫格导航数据
    const gridItems = [
      {
        id: 1,
        name: '美食',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 2,
        name: '购物',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 3,
        name: '酒店',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 4,
        name: '娱乐',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 5,
        name: '丽人',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 6,
        name: '景点',
        iconUrl: '/images/coupon.png'
      },
      {
        id: 7,
        name: '运动',
        iconUrl: '/images/coupon.png'
      }
    ];

    this.setData({
      gridItems: gridItems
    });
  },

  /**
   * 加载公告数据
   */
  loadNotices() {
    // 模拟公告数据
    const notices = [
      {
        id: 1,
        content: '欢迎使用我们的小程序，新用户可享受首单立减10元优惠!'
      },
      {
        id: 2,
        content: '本周末全场满100减20，快来选购吧！'
      },
      {
        id: 3,
        content: '新店开业，全场8.8折优惠，优惠多多！'
      }
    ];

    this.setData({
      notices: notices
    });
  },

  /**
   * 加载店铺列表数据
   */
  loadStores() {
    const { pageNum, pageSize, stores, keyword } = this.data;
    
    if (this.data.noMoreData) return;
    
    this.setData({ isLoading: true });

    // 模拟网络请求，实际项目中应该从服务器获取数据
    setTimeout(() => {
      // 模拟店铺数据
      const newStores = [
        {
          id: stores.length + 1,
          name: '品味轩餐厅',
          coverUrl: 'https://img.yzcdn.cn/vant/cat.jpeg',
          address: '北京市朝阳区建国路88号',
          tags: ['中餐', '家常菜', '聚餐'],
          rating: 4.8,
          distance: 1.2
        },
        {
          id: stores.length + 2,
          name: '星巴克咖啡(国贸店)',
          coverUrl: 'https://img.yzcdn.cn/vant/tree.jpg',
          address: '北京市朝阳区建外大街1号国贸商城',
          tags: ['咖啡', '甜点', '西式'],
          rating: 4.5,
          distance: 2.5
        },
        {
          id: stores.length + 3,
          name: '优家便利店',
          coverUrl: 'https://img.yzcdn.cn/vant/sand.jpg',
          address: '北京市海淀区中关村南大街5号',
          tags: ['便利店', '零食', '日用品'],
          rating: 4.2,
          distance: 0.5
        }
      ];
      
      // 模拟搜索过滤
      let filteredStores = newStores;
      if (keyword) {
        filteredStores = newStores.filter(store => 
          store.name.indexOf(keyword) >= 0 ||
          store.address.indexOf(keyword) >= 0 ||
          store.tags.some(tag => tag.indexOf(keyword) >= 0)
        );
      }
      
      // 模拟没有更多数据的情况
      const noMoreData = pageNum >= 3;
      
      this.setData({
        stores: [...stores, ...filteredStores],
        isLoading: false,
        noMoreData: noMoreData,
        pageNum: pageNum + 1
      });
    }, 1000);
  },

  /**
   * 点击轮播图事件处理
   */
  onBannerTap(e) {
    const id = e.currentTarget.dataset.id;
    const banner = this.data.banners.find(item => item.id === id);
    if (banner && banner.linkUrl) {
      wx.navigateTo({
        url: banner.linkUrl
      });
    }
  },

  /**
   * 点击宫格项事件处理
   */
  onGridItemTap(e) {
    const id = e.currentTarget.dataset.id;
    const item = this.data.gridItems.find(item => item.id === id);
    if (item) {
      wx.navigateTo({
        url: `/pages/category/index?id=${id}&name=${item.name}`
      });
    }
  },

  /**
   * 点击公告事件处理
   */
  onNoticeTap(e) {
    const id = e.currentTarget.dataset.id;
    const notice = this.data.notices.find(item => item.id === id);
    if (notice) {
      wx.showModal({
        title: '公告详情',
        content: notice.content,
        showCancel: false
      });
    }
  },

  /**
   * 点击店铺事件处理
   */
  onStoreTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/store/detail?id=${id}`
    });
  },

  /**
   * 搜索输入处理
   */
  onSearchInput(e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  /**
   * 搜索确认处理
   */
  onSearchConfirm(e) {
    this.setData({
      stores: [],
      pageNum: 1,
      noMoreData: false
    }, () => {
      this.loadStores();
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 下拉刷新，重置数据并重新加载
    this.setData({
      stores: [],
      pageNum: 1,
      noMoreData: false
    }, () => {
      this.loadBanners();
      this.loadGridItems();
      this.loadNotices();
      this.loadStores();
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 上拉加载更多
    if (!this.data.isLoading && !this.data.noMoreData) {
      this.loadStores();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '发现好店，品味生活',
      path: '/pages/main/index'
    };
  },
  onFranchise(){
    wx.navigateTo({
      url: '/pages/store/franchis/index'
    })
  }
})